package org.jeecg.modules.power.controller;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.power.entity.PowerSwitch;
import org.jeecg.modules.power.entity.RegAllon;
import org.jeecg.modules.power.mapper.PowerSwitchMapper;
import org.jeecg.modules.power.service.IPowerLogService;
import org.jeecg.modules.power.service.IPowerSwitchService;
import java.util.Date;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.StringEntity;
import org.jeecg.modules.power.entity.PowerLog;

 /**
 * @Description: 电源开关
 * @Author: jeecg-boot
 * @Date:   2024-03-25
 * @Version: V1.0
 */
@Slf4j
@Api(tags="电源开关")
@RestController
@RequestMapping("/power/powerSwitch")
public class PowerSwitchController extends JeecgController<PowerSwitch, IPowerSwitchService> {
	@Autowired
	private IPowerSwitchService powerSwitchService;

	 @Autowired
	 private SysDepartMapper sysDepartMapper;

	 @Autowired
	 private PowerSwitchMapper powerSwitchMapper;
	 private String ddkurl = "https://openapi.devcld.com";

	 @Autowired
	 private IPowerLogService powerLogService;
	/**
	 * 分页列表查询
	 *
	 * @param powerSwitch
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "电源开关-分页列表查询")
	@ApiOperation(value="电源开关-分页列表查询", notes="电源开关-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(PowerSwitch powerSwitch,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
		Result<List<PowerSwitch>> result = new Result<>();

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(!sysUser.getUsername().equals("admin")){
			//获取用户当前部门id
			String departId = sysDepartMapper.queryDepartIdByOrgCode(sysUser.getOrgCode());
			powerSwitch.setCid(departId);
        }
//		if(powerSwitch.getName()!=null){
//			queryWrapper.eq("name",powerSwitch.getName());
//		}

		Page<PowerSwitch> page = new Page<PowerSwitch>(pageNo, pageSize);
		IPage<PowerSwitch> pageList = powerSwitchMapper.getPage(page, powerSwitch);

		if(pageList.getRecords().size()==0){
			result.setSuccess(false);
			return result;
		}
		//把点点控设备id拼接成字符串用逗号隔开
		String ddkid = "";
		for(PowerSwitch ps:pageList.getRecords()){
			ps.setStatus("0");
			ddkid += ps.getDdkid()+",";
		}
		//去掉最后一个逗号
		ddkid = ddkid.substring(0,ddkid.length()-1);

		// 创建HttpClient对象 get请求 https的请求 带有basic认证的
		SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
		CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
		//创建get请求对象
		HttpGet httpGet = new HttpGet(ddkurl + "/device/rest/1.0/device/online/filtered?ids=" + ddkid);
		//接口有basic认证，Username是a9dc0e17001a401384a253794c7719ad, Password是b89ce8c6040d4bd8b4f1ac2c7765ad1f
		String encoding = DatatypeConverter.printBase64Binary("a9dc0e17001a401384a253794c7719ad:b89ce8c6040d4bd8b4f1ac2c7765ad1f".getBytes("UTF-8"));
		httpGet.setHeader("Authorization", "Basic " + encoding);
		//httpGet.setHeader("Authorization", "Basic YTlkYzBlMTcwMDFhNDAxMzg0YTI1Nzk0Yzc3MTlhZGY6Yjg5Y2U4YzYwNGQ0YmQ4YjRmMWFjMmM3NzY1YWQxZjM=");

		//设置请求参数
		httpGet.setHeader("Content-Type", "application/json");
		httpGet.setHeader("Accept-Charset", "UTF-8");
		//设置get请求参数
		HttpResponse httpResponse = httpClient.execute(httpGet);
		int statusCode = httpResponse.getStatusLine().getStatusCode();
		String responseBody = EntityUtils.toString(httpResponse.getEntity());

		if (statusCode == 200) {
			// 处理响应成功的情况
			Map<String, Object> map = JSON.parseObject(responseBody);

			// 获取"data"字段对应的值，它是一个List
			List<Object> dataList = (List<Object>) map.get("data");
			if(dataList != null && dataList.size() != 0) {

				// 遍历列表并打印每个元素
				for (Object value : dataList) {
					//把pageList.getRecords()的设备id和dataList的设备id做对比，如果相等就赋值online状态
					for (PowerSwitch ps : pageList.getRecords()) {
						if (ps.getDdkid().equals(value.toString())) {
							ps.setStatus("1");
						}
					}
					System.out.println(value);
				}
			}
		} else {
			// 处理响应失败的情况
			log.error("responseStatusCode: " + statusCode);
			log.error("responseBody: " + responseBody);
			throw new HttpResponseException(statusCode, responseBody);
		}


		return Result.ok(pageList);
	}
	
	/**
	 * 添加
	 *
	 * @param powerSwitch
	 * @return
	 */
	@AutoLog(value = "电源开关-添加")
	@ApiOperation(value="电源开关-添加", notes="电源开关-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody PowerSwitch powerSwitch) {
		powerSwitchService.save(powerSwitch);
		return Result.ok("添加成功！");
	}
	
	/**
	 * 编辑
	 *
	 * @param powerSwitch
	 * @return
	 */
	@AutoLog(value = "电源开关-编辑")
	@ApiOperation(value="电源开关-编辑", notes="电源开关-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody PowerSwitch powerSwitch) {
		powerSwitchService.updateById(powerSwitch);
		return Result.ok("编辑成功!");
	}
	
	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "电源开关-通过id删除")
	@ApiOperation(value="电源开关-通过id删除", notes="电源开关-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		powerSwitchService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "电源开关-批量删除")
	@ApiOperation(value="电源开关-批量删除", notes="电源开关-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.powerSwitchService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "电源开关-通过id查询")
	@ApiOperation(value="电源开关-通过id查询", notes="电源开关-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		PowerSwitch powerSwitch = powerSwitchService.getById(id);
		return Result.ok(powerSwitch);
	}

	 @AutoLog(value = "电源开关-一键全开关")
	 @ApiOperation(value="电源开关-一键全开关", notes="电源开关-一键全开关")
	 @PostMapping(value = "/regAll")
	 public Result<?> regAll(@RequestBody RegAllon regAllon) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnsupportedEncodingException {
		 // 创建HttpClient对象 get请求 https的请求 带有basic认证的
		 SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
		 CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
		 //创建get请求对象
		 HttpPost httpPost = new HttpPost(ddkurl + "/device/rest/1.0/device/reg/all" );
		 //接口有basic认证，Username是a9dc0e17001a401384a253794c7719ad, Password是b89ce8c6040d4bd8b4f1ac2c7765ad1f
		 String encoding = DatatypeConverter.printBase64Binary("a9dc0e17001a401384a253794c7719ad:b89ce8c6040d4bd8b4f1ac2c7765ad1f".getBytes("UTF-8"));
		 httpPost.setHeader("Authorization", "Basic " + encoding);
		 httpPost.setHeader("Content-Type", "application/json");
		 httpPost.setHeader("Accept-Charset", "UTF-8");
		 try {
			 //设置请求参数
			 JSONObject json = new JSONObject();
			 json.put("deviceId", regAllon.getDdkid());
			 json.put("status", regAllon.getStatus().equals("1"));
			 StringEntity entity = new StringEntity(json.toString(), "UTF-8");
			 httpPost.setEntity(entity);
			 //执行请求
			 HttpResponse httpResponse = httpClient.execute(httpPost);
			 int statusCode = httpResponse.getStatusLine().getStatusCode();
			 String responseBody = EntityUtils.toString(httpResponse.getEntity());

		 }catch (Exception e) {
			 e.printStackTrace();
		 }
		 PowerLog powerLog = new PowerLog();

		 powerLog.setSid(powerSwitchMapper.getId(regAllon.getDdkid()));
		 powerLog.setZkname("全部");
		 powerLog.setOnoff(regAllon.getStatus());
		 powerLogService.save(powerLog);
		 return Result.ok("请求成功");
	 }
	 @ApiOperation(value="首页数据统计", notes="首页数据统计")
	 @GetMapping(value = "/homes")
	 public Result<?> homes(HttpServletRequest req) throws NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException {
		 JSONObject json = new JSONObject();

		 json.put("departcnt",sysDepartMapper.getcnt());
		 json.put("power",powerSwitchMapper.getcnt());

		 QueryWrapper<PowerSwitch> queryWrapper = new QueryWrapper<PowerSwitch>();
		 queryWrapper.eq("del_flag",0);

		 Page<PowerSwitch> page = new Page<PowerSwitch>(1, 9999);
		 IPage<PowerSwitch> pageList = powerSwitchService.page(page, queryWrapper);
		 if(pageList.getRecords().size()==0){
			 return Result.error("未查询到数据");
		 }
		 //把点点控设备id拼接成字符串用逗号隔开
		 String ddkid = "";
		 for(PowerSwitch ps:pageList.getRecords()){
			 ps.setStatus("0");
			 ddkid += ps.getDdkid()+",";
		 }
		 //去掉最后一个逗号
		 ddkid = ddkid.substring(0,ddkid.length()-1);

		 // 创建HttpClient对象 get请求 https的请求 带有basic认证的
		 SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
		 CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
		 //创建get请求对象
		 HttpGet httpGet = new HttpGet(ddkurl + "/device/rest/1.0/device/online/filtered?ids=" + ddkid);
		 //接口有basic认证，Username是a9dc0e17001a401384a253794c7719ad, Password是b89ce8c6040d4bd8b4f1ac2c7765ad1f
		 String encoding = DatatypeConverter.printBase64Binary("a9dc0e17001a401384a253794c7719ad:b89ce8c6040d4bd8b4f1ac2c7765ad1f".getBytes("UTF-8"));
		 httpGet.setHeader("Authorization", "Basic " + encoding);
		 //httpGet.setHeader("Authorization", "Basic YTlkYzBlMTcwMDFhNDAxMzg0YTI1Nzk0Yzc3MTlhZGY6Yjg5Y2U4YzYwNGQ0YmQ4YjRmMWFjMmM3NzY1YWQxZjM=");

		 //设置请求参数
		 httpGet.setHeader("Content-Type", "application/json");
		 httpGet.setHeader("Accept-Charset", "UTF-8");
		 //设置get请求参数
		 HttpResponse httpResponse = httpClient.execute(httpGet);
		 int statusCode = httpResponse.getStatusLine().getStatusCode();
		 String responseBody = EntityUtils.toString(httpResponse.getEntity());

		 if (statusCode == 200) {
			 // 处理响应成功的情况
			 Map<String, Object> map = JSON.parseObject(responseBody);

			 // 获取"data"字段对应的值，它是一个List
			 List<Object> dataList = (List<Object>) map.get("data");
			 json.put("onLine",dataList.size());
			 // 遍历列表并打印每个元素
		 } else {
			 // 处理响应失败的情况
			 log.error("responseStatusCode: " + statusCode);
			 log.error("responseBody: " + responseBody);
			 throw new HttpResponseException(statusCode, responseBody);
		 }


		 return Result.ok(json);
	 }

	 @ApiOperation(value="获取公司列表", notes="获取公司列表")
	 @GetMapping(value = "/getDepart")
	 public Result<?> getDepart(HttpServletRequest req) {
		 List<SysDepart> sysDepart = sysDepartMapper.getDepart();
		 return Result.ok(sysDepart);
	 }
 }
